﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace MvcPresenter.Models
{
	public class StoragePresentationRepository : IPresentationRepository
	{
		private readonly string _path;
		private readonly List<Presentation> _presentations = new List<Presentation>();

		public StoragePresentationRepository(string path)
		{
			_path = path;

			// 都度ファイル読み込みは重いけどね！
			foreach (var dir in Directory.GetDirectories(path))
			{
				var name = Path.GetFileName(dir);
                var presentation = StorageAccessor.Load(path, false, name);

				_presentations.Add(presentation);
			}
		}

		public Presentation GetByName(string name)
		{
			return _presentations.Where(p => p.Name == name).FirstOrDefault();
		}

		public IEnumerable<Presentation> List()
		{
			return _presentations;
		}

		public void Delete(string name)
		{
			Presentation presen = GetByName(name);
			if (presen == null)
				throw new ArgumentException("ないです", "name");

			presen.State = DataState.Deleted;
		}

		public void Create(Presentation presentation)
		{
			var model = GetByName(presentation.Name);
			if (model != null)
				_presentations.Remove(model);

			presentation.State = DataState.Inserting;
			_presentations.Add(presentation);
		}

		public void SubmitChanges()
		{
			foreach (var presentation in _presentations)
			{
				switch (presentation.State)
				{
					case DataState.Inserting:
						StorageAccessor.Save(PresentationZipValueProviderFactory.UploadTempPath, _path, presentation);
						break;
					case DataState.Changed:
						break;
					case DataState.Deleted:
						StorageAccessor.Delete(_path, presentation);
						break;
				}
			}
		}
	}
}